package com.kun.companion.core.persistence.rule;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.StrPool;
import com.kun.companion.core.exception.Assert;
import com.kun.companion.core.persistence.strategy.SerializationStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

/**
 * 单文件规则
 *
 * @author gzc
 * @since 2024/8/21
 **/
public class SingletonFileRuler implements FileCreateRule {
    private final static Logger log = LoggerFactory.getLogger(SingletonFileRuler.class);
    private final String fileName;

    public SingletonFileRuler(String fileName) {
        this.fileName = fileName;
    }

    @Override
    public String getOutputFileName() {
        return this.fileName;
    }

    @Override
    public String getInputFilePath(String baseStorageDirPath, SerializationStrategy<?> strategy) {
        if (FileUtil.isFile(baseStorageDirPath)) {
            Assert.throwBizException("参数 -> {}，不能是文件！", baseStorageDirPath);
        }
        String inputFilePath = "";
        // 读取最新的缓存数据文件
        if (FileUtil.exist(baseStorageDirPath)) {
            inputFilePath = baseStorageDirPath + File.separator + this.fileName + StrPool.DOT + strategy.getFileTypeName();
        } else {
            // 创建目录
            FileUtil.mkdir(baseStorageDirPath);
        }
        return inputFilePath;
    }

    @Override
    public String getOutputFilePath(String baseStorageDirPath, SerializationStrategy<?> strategy) {
        // 确保目录存在
        FileUtil.mkdir(baseStorageDirPath);
        // 拼接输出文件完整路径
        String fileNameAndType = getOutputFileName() + StrPool.DOT + strategy.getFileTypeName();
        return baseStorageDirPath + File.separator + fileNameAndType;
    }

    @Override
    public boolean isOverride() {
        return true;
    }

}
